﻿using System;
using System.Activities;
using Reactor.Messages.Events.Failures.Adoption;
using Reactor.Workflow.Activities;

namespace Reactor.ServiceGrid.Workflows.Activities
{
    public class ConstructOrphanFailureEvent : CreateMessageActivity<OrphanFailed>
    {
        [RequiredArgument]
        public InArgument<ServiceIdentifier> ServiceIdentifier { get; set; }

        public InArgument<Exception> OrphanFailureException { get; set; }

        #region Overrides of CodeActivity<OrphanFailed>

        /// <summary>
        /// When implemented in a derived class, performs the execution of the activity.
        /// </summary>
        /// <returns>
        /// The result of the activity’s execution.
        /// </returns>
        /// <param name="context">The execution context under which the activity executes.</param>
        protected override OrphanFailed Execute(CodeActivityContext context)
        {
            // Issue advisory message stating the orphaning failed.
            var coreName = Environment.Context.GridContext.CurrentReactorService.Identifier.Name;
            var serviceIdentifier = context.GetValue(ServiceIdentifier);
            var exception = context.GetValue(OrphanFailureException);
            var failureMessage = new OrphanFailed
            {
                CoreName = coreName,
                ServiceName = serviceIdentifier.Name,
                Version = serviceIdentifier.Version.ToString(),
                Subject = string.Format("Service: '{0}' could not be orphaned by Core: {1}", serviceIdentifier, coreName),
                Description = "Details:<br />"
            };

            failureMessage.Description = exception != null ? exception.Message : "--Unspecified--";

            return failureMessage;
        }

        #endregion
    }
}
